<?php
$data = json_decode(file_get_contents("模拟数据3.json"), true)['data'];
$balance = $data['balance'];

$data = $data['order'];
//数组排序
usort($data, function ($a, $b) {
    return $a['datetime'] <=> $b['datetime'];
});
$data = array_reverse($data);
// die(var_dump($data));
$total = 0;
$ii = 1;
for ($i = 0; $i < count($data); $i++, $ii++) {
    // var_dump(empty($data[$i]['customerUid']));
    if ($i == 0) {
        $data[$i]['balance'] = $balance;
        // var_dump([
        //     'balance' => $balance,
        //     'totalAmount' => $data[$i]['totalAmount']
        // ]);
    } else {
        // array_key_exists('customerUid', );
        if (!empty($data[$i]['customerUid'])) {
            // //每笔总价 
            if (!empty($data[$i - 1]['totalAmount'])) {
                $balance += $data[$i - 1]['totalAmount'];
                $data[$i]['balance'] = $balance;
                // var_dump([
                //     'balance' => $balance,
                //     'totalAmount' => $data[$i - 1]['totalAmount']
                // ]);
            } else {
                $balance += $data[$i - 2]['totalAmount'];
                $data[$i]['balance'] = $balance;
            }
        } else {
            //会员充值

            $data[$i]['balance'] = $data[$i]['items'][0]['customerMoneyAfterRecharge'];
            $balance -= $data[$i]['items'][0]['rechargeMoney'];
            // var_dump($data[$i]['balance']);
        }

    }
}
var_dump($data);
exit;

require 'vendor/autoload.php';

use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Exception\RequestException;

use GuzzleHttp\Promise;

$GLOBALS['appID'] = "0988E21B01B60906678E6C169A2699AD";
$GLOBALS['appKey'] = '1088957707187519101';
$GLOBALS['url'] = 'https://area42-win.pospal.cn:443/';

function get_post($url, $data, $headers)
{
    $client = new Client();
    try {
        $response = $client->post($GLOBALS['url'] . $url, [
            'headers' => $headers,
            'json' => $data
        ]);
        // 输出请求结果
        return $response->getBody();
    } catch (RequestException $e) {
        // 输出请求异常
        return $e->getMessage();
    }
}

$phone = $_POST['phone'];
if (empty($phone)) {
    echo '{"code":-1,"msg":"手机号不能为空"}';
    exit;
}
$body = [
    "appId" => $GLOBALS['appID'],
    "customerTel" => $phone,
];
$headers = [
    'User-Agent' => 'openApi',
    'Content-Type' => 'application/json',
    'data-signature' => strtoupper(md5($GLOBALS['appKey'] . json_encode($body)))
];
$startTime = $_POST['startTime'];
$endTime = $_POST['endTime'];
$res = json_decode(get_post('pospal-api2/openapi/v1/customerOpenapi/queryBytel', $body, $headers));
// die(var_dump($res));
if ($res->status == 'success' && !empty($res->data)) {
    $val['categoryName'] = $res->data[0]->categoryName;
    $val['number'] = $res->data[0]->number;
    $val['name'] = $res->data[0]->name;
    $val['balance'] = $res->data[0]->balance;
    $val['phone'] = $res->data[0]->phone;
    $val['point'] = $res->data[0]->point;
    $val['discount'] = $res->data[0]->discount;
    $val['createdDate'] = $res->data[0]->createdDate;

    if (empty($res->data[0]->extInfo)) {
        $extinfo = [];
    } else {
        $extinfo = $res->data[0]->extInfo;
    }
    $val['extInfo'] = $extinfo;
    $body = [
        "appId" => $GLOBALS['appID'],
        "startTime" => $startTime,
        "endTime" => $endTime,
        "customerUid" => $res->data[0]->customerUid,
        "queryAllStoreConsume" => 1,

    ];
    $headers = [
        'User-Agent' => 'openApi',
        'Content-Type' => 'application/json',
        'data-signature' => strtoupper(md5($GLOBALS['appKey'] . json_encode($body)))
    ];
    $order = json_decode(get_post('pospal-api2/openapi/v1/ticketOpenApi/queryCustomerHistoryTicketsByUid', $body, $headers));
    /**  "items": [
         {
             "id": 406585596,
             "name": "水卤煮蛋",
             "buyPrice": 0,
             "sellPrice": 2,
             "customerPrice": 2,
             "quantity": 2,
             "discount": 100,
             "customerDiscount": 100,
             "totalAmount": 4,
             "totalProfit": 4,
             "isCustomerDiscount": 1,
             "productUid": 858411824076491008,
             "productBarcode": "2401053001972",
             "isWeighing": 0,
             "ticketitemattributes": [],
             "discountDetails": [],
             "saleGuiderList": []
         }
     ],

     */
    if ($order->status == 'success' && !empty($order->data->result)) {
        $CustomerRechargeLog = queryCustomerBalance($res->data[0]->customerUid);
        $Recharge = array_reverse($CustomerRechargeLog->data)[0];
        // die(var_dump($Recharge));
        if ($CustomerRechargeLog->status == 'success' && !empty($CustomerRechargeLog->data)) {
            // foreach ($CustomerRechargeLog->data as $key => $value) {

            //     $val1['datetime'] = $value->datetime;
            //     $val1['items'] = [
            //         [
            //             'name' => "会员充值",
            //             'datetime' => $value->datetime,
            //             'payMethod' => $value->payMethod,
            //             'giftMoney' => $value->giftMoney,//充值时赠送的金额
            //             'rechargeMoney' => $value->rechargeMoney,//充值金额
            //             'customerMoneyAfterRecharge' => $value->customerMoneyAfterRecharge,//充值后金额
            //         ]
            //     ];
            //     $val2[] = $val1;
            //     // $val1['datetime'] = $value->datetime;
            //     // $val1['items'] =
            //     // $val1['items'][] = [
            //     //     'name' => "会员充值",
            //     //     'datetime' => $value->datetime,
            //     //     'payMethod' => $value->payMethod,
            //     //     'giftMoney' => $value->giftMoney,//充值时赠送的金额
            //     //     'rechargeMoney' => $value->rechargeMoney,//充值金额
            //     //     'customerMoneyAfterRecharge' => $value->customerMoneyAfterRecharge,//充值后金额
            //     // ];
            // }
            // $val['order'] = $val2;


            $val2 = [
                [
                    'datetime' => $Recharge->datetime,
                    'items' => [
                        [
                            'name' => "会员充值",
                            'payMethod' => $Recharge->payMethod,
                            'giftMoney' => $Recharge->giftMoney,//充值时赠送的金额
                            'rechargeMoney' => $Recharge->rechargeMoney,//充值金额
                            'customerMoneyAfterRecharge' => $Recharge->customerMoneyAfterRecharge,//充值后金额
                        ]
                    ]
                ]
            ];
            $val['order'] = array_merge($order->data->result, $val2);

            //数组时间排序    
        } else {
            $val['order'] = $order->data->result;
        }
        $arr = object_to_array($val);

        // die(var_dump($arr));
        $val['order'] = Balance($arr['order'], $res->data[0]->balance);
    } else {
        $val['order'] = [];
    }
} else {
    $val = $res->messages[0];
}
echo json_encode([
    'code' => 1,
    'data' => $val
]);

//统计每笔余额
function Balance($data, $balance)
{

    //数组排序
    usort($data, function ($a, $b) {
        return $a['datetime'] <=> $b['datetime'];
    });
    $data = array_reverse($data);

    $total = 0;
    $ii = 1;
    for ($i = 0; $i < count($data); $i++, $ii++) {

        if ($i == 0) {
            $data[$i]['balance'] = $balance;

        } else {

            if (!empty($data[$i]['customerUid'])) {
                // //每笔总价 
                if (!empty($data[$i - 1]['totalAmount'])) {
                    $balance += $data[$i - 1]['totalAmount'];
                    $data[$i]['balance'] = $balance;
                }
            } else {
                //会员充值
                $data[$i]['balance'] = $data[$i]['items'][0]['customerMoneyAfterRecharge'];
                $balance -= $data[$i]['items'][0]['rechargeMoney'];

            }

        }
    }
    return $data;
}
function object_to_array($object)
{
    if ($object === null) {
        return [];
    } else {
        return json_decode(json_encode($object), true);
    }
}
// 查询用户余额
function queryCustomerBalance($customerUid)
{
    $body = [
        "appId" => $GLOBALS['appID'],
        "customerUid" => $customerUid,
    ];
    $headers = [
        'User-Agent' => 'openApi',
        'Content-Type' => 'application/json',
        'data-signature' => strtoupper(md5($GLOBALS['appKey'] . json_encode($body)))
    ];
    return json_decode(get_post('pospal-api2/openapi/v1/customerOpenApi/queryCustomerRechargeLog', $body, $headers));
}
